const _ = require('lodash');
module.exports = app => {
  return async (ctx, next) => {
    const {socket, logger} = ctx;
    const id = socket.id;
    let {token, name} = ctx.query;

    const kick = (id, msg) => {
      console.error('#socket.io tick', id, msg);

      // 踢出用户前发送消息
      socket.emit('connect_error', msg);

      // 调用 adapter 方法踢出用户，客户端触发 disconnect 事件
      setTimeout(() => {
        socket.disconnect();
      }, 500);
    };

    if (_.isEmpty(token))
      return kick(id, '截图程序 缺少Token 不允许连接');
    if (_.isEmpty(name))
      return kick(id, '截图程序 缺少名称 不允许连接');

    let serverToken = await ctx.model.Config.get('screenshotToken', null);

    if (_.isEmpty(serverToken))
      return kick(id, '服务器没有设置截图Token，拒绝所有截图程序连接');

    if (token !== serverToken)
      return kick(id, 'Socket.io Token不匹配');

    //发送配置给客户端
    socket.emit('config', {parallel: 1});
    let redisKey = app.config.screenshot.redisClientKey + id;
    //客户端名称后加随机字符
    name += ' ' + Math.random().toString(36).slice(2, 6);
    await app.redis.set(redisKey, JSON.stringify({
      name,
      id: ctx.id,
      started_at: Date.now(),
      success: 0,
      fail: 0,
      wait: 0,
    }));
    socket.on('disconnect', () => {
      console.log('截图程序断开链接');
      app.redis.del(redisKey);
    });
    await next();
  };
};